package cc.cc4414.spring.mybatis.crypto.impl;

import cc.cc4414.spring.mybatis.config.MybatisProperties;
import cc.cc4414.spring.mybatis.crypto.ICryptService;
import cn.hutool.crypto.symmetric.AES;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;

/**
 * 数据库数据加解密接口默认实现类
 *
 * @author cc 2021年2月24日
 */
@Service
@RequiredArgsConstructor
@ConditionalOnMissingBean(ICryptService.class)
@Slf4j
public class CryptServiceImpl implements ICryptService {

    private final MybatisProperties mybatisProperties;

    @Override
    public String encrypt(String data) {
        AES aes = new AES(mybatisProperties.getKey().getBytes());
        return aes.encryptBase64(data);
    }

    @Override
    public String decrypt(String data) {
        AES aes = new AES(mybatisProperties.getKey().getBytes());
        String text = data;
        try {
            text = aes.decryptStr(data);
        } catch (Exception e) {
            log.warn("数据解密失败: {}", data);
        }
        return text;
    }
}
